/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jili.ubert.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 *
 * @author ChengJiLi
 */
public class MsgEncoder extends MessageToByteEncoder<MsgEntity> {

    @Override
    protected void encode(ChannelHandlerContext ctx, MsgEntity msg, ByteBuf byteBuf) throws Exception {
        int dataLength = msg.getData() == null ? 0 : msg.getData().length;
        byteBuf.ensureWritable(4 + dataLength);
        byteBuf.writeInt(dataLength);
        byteBuf.writeInt(msg.getCmdCode());
        byteBuf.writeInt(msg.getSessionID());
        if (dataLength > 0) {
            msg.getData()[0] = (byte) (msg.getData()[0] + 1);
            byteBuf.writeBytes(msg.getData());
        }
    }
}
